#include						"TcpClient.h"

TcpClient::TcpClient(PacketHandler *packet) : _packet(packet)
{
	_lastId = 0;
}

TcpClient::~TcpClient()
{
}

quint16								TcpClient::addServer(const std::string & ip, const std::string & port)
{
	QtAsyncTcpSocket				*socket = new QtAsyncTcpSocket();

	_lastId = _lastId++;

	socket->setHandler(_packet);
	socket->init();
	_sockets[_lastId] = socket;
	_sockets[_lastId]->connectToHost(ip, port);
	initConnect(*_sockets[_lastId]);

	return _lastId;
}

void								TcpClient::initConnect(QtAsyncTcpSocket &socket)
{
	connect(&socket, SIGNAL(connected(QHostAddress &)), this, SLOT(handleConnect(QHostAddress &)));
	connect(&socket, SIGNAL(disconnected(QHostAddress &)), this, SLOT(handleDisconnect(QHostAddress &)));
}

void								TcpClient::sendPacket(Packet* pkg, quint16 id)
{
	if (id > 0)
		_sockets[id]->sendPacket(pkg);
	//else
	//	sendToEveryone(pkg);
}

void								TcpClient::removeClient(quint16 id)
{
	QtAsyncTcpSocket *tmp = _sockets[id];
	_sockets.erase(id);
	tmp->deleteLater();
}

QHostAddress 						TcpClient::getIp(quint16 id)
{
	return _sockets[id]->getIp();
}

quint16								TcpClient::getId(QHostAddress& ip)
{
	typedef std::map<quint16,QtAsyncTcpSocket*>::iterator it_sockets;

	for(it_sockets it = _sockets.begin(); it != _sockets.end(); ++it)
	{
		if (it->second->getIp() == ip)
			return it->first;
	}
	return 0;
}

bool								TcpClient::isInside(quint16 id)
{
	if (_sockets.count(id) > 0)
		return true;
	return false;
}

bool								TcpClient::isInside(QHostAddress& ip)
{
	typedef std::map<quint16,QtAsyncTcpSocket*>::iterator it_sockets;
	
	for(it_sockets it = _sockets.begin(); it != _sockets.end(); it++)
	{
		if (it->second->getIp() == ip)
			return true;
	}
	return false;
}

void								TcpClient::handleConnect(QHostAddress &ip)
{
	emit connected(ip);
}

void								TcpClient::handleDisconnect(QHostAddress &ip)
{
	emit disconnected(ip);
}